/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cetc.iframe;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.swing.table.DefaultTableModel;

import com.cetc.Item;
import com.cetc.dao.Dao;
import com.cetc.dao.model.TbSpinfo;

public class ShangPinChaXun extends javax.swing.JInternalFrame {

    /**
     * Creates new form ShangPinChaXun
     */
    public ShangPinChaXun() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jFrame1 = new javax.swing.JFrame();
        jMenu3 = new javax.swing.JMenu();
        jPopupMenu1 = new javax.swing.JPopupMenu();
        jLabel1 = new javax.swing.JLabel();
        conditionContent = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        conditionName = new javax.swing.JComboBox<>();
        conditionOperation = new javax.swing.JComboBox<>();
        queryButton = new javax.swing.JButton();
        showAllButton = new javax.swing.JButton();

        jMenu1.setText("jMenu1");

        jMenu2.setText("jMenu2");

        jMenuItem1.setText("jMenuItem1");

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jMenu3.setText("jMenu3");

        setClosable(true);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("商品信息查询");
        setPreferredSize(new java.awt.Dimension(600, 300));

        jLabel1.setText("选择查询条件：");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                
            },
            new String [] {
            	"客户ID", "商品名称", "简称", "产地", "单位", "规格", "包装", "批号", "批准文号", "供应商全称", "备注"
            }
        ));
        jTable1.setRowHeight(24);
        jScrollPane1.setViewportView(jTable1);
        jTable1.setEnabled(false);// 设置表格模型无法响应用户输入

        conditionName.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "商品名称", "供应商全称", "产地", "规格" }));

        conditionOperation.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "等于", "包含" }));

        queryButton.setText("查询");
        
        final DefaultTableModel dftm = (DefaultTableModel) jTable1.getModel();// 获得默认表格模型
        queryButton.addActionListener(new QueryAction(dftm));

        showAllButton.setText("显示全部数据");
        
        showAllButton.addActionListener(new ActionListener() {
			public void actionPerformed(final ActionEvent e) {
				conditionContent.setText("");// 设置“条件内容”文本框为空
				List list = Dao.getSpInfos();// 获取所有商品信息的集合
				updateTable(list, dftm);// 更新表格内容
			}
		});

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(conditionName, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(conditionOperation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(conditionContent)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(queryButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(showAllButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(conditionName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(conditionContent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(conditionOperation, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(queryButton)
                    .addComponent(showAllButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 217, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    // 条件查询
 	private final class QueryAction implements ActionListener {
 		private final DefaultTableModel dftm;// 默认的表格模型
 		private QueryAction(DefaultTableModel dftm) {// 区分同名变量，并为同名变量赋值
 			this.dftm = dftm;
 		}
 		public void actionPerformed(final ActionEvent e) {
 			String conName, conOperation, content;// 声明String型的“条件名称”、“条件运算”、“条件内容”
 			conName = conditionName.getSelectedItem().toString().trim();// 获得“条件名称”
 			conOperation = conditionOperation.getSelectedItem().toString();// 获得“条件运算”
 			content = conditionContent.getText().trim();// 获得“条件内容”
 			List list = null;// 声明“商品信息”的集合
 			list = searchInfo(conName, conOperation, content, list);// 获得符合条件的“商品信息”集合
 			updateTable(list, dftm);// 更新表格内容
 		}
 		// 拼接SQL语句，并获得执行SQL语句后相应的结果集
 		private List searchInfo(String conName, String conOperation,
 				String content, List list) {
 			String sql = "select * from Tb_Spinfo where ";// 初始化SQL语句
 			if (conOperation.equals("等于")) {// “条件运算”为“等于”
 				if (conName.equals("商品名称"))// “条件名称”为“商品名称”
 					list = Dao.findForList(sql + "spname='" + content + "'");// 获得某一“商品名称”的“商品信息”集合
 				if (conName.equals("供应商全称"))// “条件名称”为“供应商全称”
 					list = Dao.findForList(sql + "gysname='" + content + "'");// 获得某一“供应商全称”的“商品信息”集合
 				if (conName.equals("产地"))// “条件名称”为“产地”
 					list = Dao.findForList(sql + "cd='" + content + "'");// 获得某一“产地”的“商品信息”集合
 				if (conName.equals("规格"))// “条件名称”为“规格”
 					list = Dao.findForList(sql + "gg='" + content + "'");// 获得某一“规格”的“商品信息”集合
 			} else {
 				if (conName.equals("商品名称"))// “条件名称”为“商品名称”
 					list = Dao.findForList(sql + "spname like '%" + content + "%'");// 获得“商品名称”中含有“条件内容”的“商品信息”集合
 				if (conName.equals("供应商全称"))// “条件名称”为“供应商全称”
 					list = Dao.findForList(sql + "gysname like '%" + content + "%'");// 获得“供应商全称”中含有“条件内容”的“商品信息”集合
 				if (conName.equals("产地"))// “条件名称”为“产地”
 					list = Dao.findForList(sql + "cd like '%" + content + "%'");// 获得“产地”中含有“条件内容”的“商品信息”集合
 				if (conName.equals("规格"))// “条件名称”为“规格”
 					list = Dao.findForList(sql + "gg like '%" + content + "%'");// 获得“规格”中含有“条件内容”的“商品信息”集合
 			}
 			return list;
 		}
 	}
 	
 	// 点击“显示全部数据”按钮后，更新表格内容
 	private void updateTable(List list, final DefaultTableModel dftm) {
 		int num = dftm.getRowCount();// 获得表格模型中的行数
 		for (int i = 0; i < num; i++)
 			dftm.removeRow(0);// 移除表格模型中的第一行
 		Iterator iterator = list.iterator();// 创建所有商品信息的集合的迭代器
 		TbSpinfo spInfo;// 商品信息
 		while (iterator.hasNext()) {// 所有商品信息的集合中仍有元素可以迭代
 			List info = (List) iterator.next();// 获得迭代的下一个集合
 			Item item = new Item();// 数据表公共类
 			item.setId((String) info.get(0));// 编号属性
 			item.setName((String) info.get(1));// 名称信息
 			spInfo = Dao.getSpInfo(item);// 读取商品信息
 			Vector rowData = new Vector();// 创建向量
 			rowData.add(spInfo.getId().trim());// 商品编号
 			rowData.add(spInfo.getSpname().trim());// 商品名称
 			rowData.add(spInfo.getJc());// 商品简称
 			rowData.add(spInfo.getCd());// 产地
 			rowData.add(spInfo.getDw());// 商品计量单位
 			rowData.add(spInfo.getGg());// 商品规格
 			rowData.add(spInfo.getBz());// 包装
 			rowData.add(spInfo.getPh());// 批号
 			rowData.add(spInfo.getPzwh());// 批准文号
 			rowData.add(spInfo.getGysname());// 供应商名称
 			rowData.add(spInfo.getMemo());// 备注
 			dftm.addRow(rowData);// 向表格对象添加行数据（商品信息）
 		}
 	}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ShangPinChaXun.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ShangPinChaXun.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ShangPinChaXun.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ShangPinChaXun.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ShangPinChaXun().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField conditionContent;
    private javax.swing.JComboBox conditionName;
    private javax.swing.JComboBox conditionOperation;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPopupMenu jPopupMenu1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JButton queryButton;
    private javax.swing.JButton showAllButton;
    // End of variables declaration//GEN-END:variables
}
